package com.yuanqi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanqi.dto.PurchaseReturnOrderDTO;
import com.yuanqi.pojo.Customer;
import com.yuanqi.pojo.PurchaseReturnOrder;
import com.yuanqi.pojo.PurchaseReturnOrderItem;
import com.yuanqi.pojo.SalesOrder;
import com.yuanqi.service.CustomerService;
import com.yuanqi.service.PurchaseReturnOrderItemService;
import com.yuanqi.service.PurchaseReturnOrderService;
import com.yuanqi.service.SalesOrderService;
import com.yuanqi.mapper.PurchaseReturnOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 退货订单服务实现类
 */
@Service
public class PurchaseReturnOrderServiceImpl extends ServiceImpl<PurchaseReturnOrderMapper, PurchaseReturnOrder>
    implements PurchaseReturnOrderService {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private SalesOrderService salesOrderService;

    @Autowired
    private PurchaseReturnOrderItemService purchaseReturnOrderItemService;

    @Override
    @Transactional
    public PurchaseReturnOrderDTO createReturnOrder(PurchaseReturnOrderDTO returnOrderDTO) {
        PurchaseReturnOrder returnOrder = returnOrderDTO.getReturnOrder();

        // 设置退货订单基本信息
        returnOrder.setReturnOrderCode(generateReturnOrderCode());
        returnOrder.setStatus(0); // 待审核状态
        returnOrder.setReturnDate(new Date());
        returnOrder.setCreatedAt(new Date());
        returnOrder.setUpdatedAt(new Date());

        // 保存退货订单
        save(returnOrder);

        // 保存退货明细
        if (returnOrderDTO.getItems() != null && !returnOrderDTO.getItems().isEmpty()) {
            for (PurchaseReturnOrderItem item : returnOrderDTO.getItems()) {
                item.setReturnOrderId(returnOrder.getId());
            }
            purchaseReturnOrderItemService.saveBatchItems(returnOrderDTO.getItems());
        }

        // 计算退货总金额
        calculateReturnAmount(returnOrderDTO);

        return returnOrderDTO;
    }

    @Override
    @Transactional
    public boolean updateReturnOrder(PurchaseReturnOrderDTO returnOrderDTO) {
        PurchaseReturnOrder returnOrder = returnOrderDTO.getReturnOrder();

        // 检查退货订单状态
        PurchaseReturnOrder existingOrder = getById(returnOrder.getId());
        if (existingOrder == null) {
            throw new RuntimeException("退货订单不存在");
        }

        if (existingOrder.getStatus() != 0) {
            throw new RuntimeException("只有待审核状态的退货订单可编辑");
        }

        // 更新退货订单基本信息
        returnOrder.setUpdatedAt(new Date());
        boolean orderUpdated = updateById(returnOrder);

        // 删除原有明细
        purchaseReturnOrderItemService.deleteByReturnOrderId(returnOrder.getId());

        // 保存新的明细
        if (returnOrderDTO.getItems() != null && !returnOrderDTO.getItems().isEmpty()) {
            for (PurchaseReturnOrderItem item : returnOrderDTO.getItems()) {
                item.setReturnOrderId(returnOrder.getId());
            }
            purchaseReturnOrderItemService.saveBatchItems(returnOrderDTO.getItems());
        }

        // 计算退货总金额
        calculateReturnAmount(returnOrderDTO);

        return orderUpdated;
    }

    @Override
    public PurchaseReturnOrderDTO getReturnOrderDetail(Long returnOrderId) {
        // 获取退货订单基本信息
        PurchaseReturnOrder returnOrder = getById(returnOrderId);
        if (returnOrder == null) {
            return null;
        }

        // 获取退货明细
        List<PurchaseReturnOrderItem> items = purchaseReturnOrderItemService.getItemsByReturnOrderId(returnOrderId);

        // 获取客户信息
        Customer customer = customerService.getById(returnOrder.getCustomerId());

        // 获取原销售订单信息
        SalesOrder salesOrder = salesOrderService.getById(returnOrder.getSalesOrderId());

        // 构建DTO
        PurchaseReturnOrderDTO dto = new PurchaseReturnOrderDTO();
        dto.setReturnOrder(returnOrder);
        dto.setItems(items);
        dto.setCustomerName(customer != null ? customer.getCustomerName() : "");
        dto.setOriginalOrderCode(salesOrder != null ? salesOrder.getSoCode() : "");

        // 计算退货总金额
        calculateReturnAmount(dto);

        return dto;
    }

    @Override
    public IPage<PurchaseReturnOrderDTO> pageReturnOrders(Page<PurchaseReturnOrder> page, String returnOrderCode, Long customerId, Integer status) {
        // 构建查询条件
        LambdaQueryWrapper<PurchaseReturnOrder> wrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(returnOrderCode)) {
            wrapper.like(PurchaseReturnOrder::getReturnOrderCode, returnOrderCode);
        }

        if (customerId != null) {
            wrapper.eq(PurchaseReturnOrder::getCustomerId, customerId);
        }

        if (status != null) {
            wrapper.eq(PurchaseReturnOrder::getStatus, status);
        }

        wrapper.orderByDesc(PurchaseReturnOrder::getCreatedAt);

        // 分页查询
        IPage<PurchaseReturnOrder> returnOrderPage = page(page, wrapper);

        // 转换为DTO
        IPage<PurchaseReturnOrderDTO> dtoPage = new Page<>();
        dtoPage.setCurrent(returnOrderPage.getCurrent());
        dtoPage.setSize(returnOrderPage.getSize());
        dtoPage.setTotal(returnOrderPage.getTotal());
        dtoPage.setPages(returnOrderPage.getPages());

        List<PurchaseReturnOrderDTO> dtoList = returnOrderPage.getRecords().stream()
                .map(order -> {
                    PurchaseReturnOrderDTO dto = new PurchaseReturnOrderDTO();
                    dto.setReturnOrder(order);

                    // 获取客户信息
                    Customer customer = customerService.getById(order.getCustomerId());
                    dto.setCustomerName(customer != null ? customer.getCustomerName() : "");

                    // 获取原销售订单信息
                    SalesOrder salesOrder = salesOrderService.getById(order.getSalesOrderId());
                    dto.setOriginalOrderCode(salesOrder != null ? salesOrder.getSoCode() : "");

                    return dto;
                })
                .collect(java.util.stream.Collectors.toList());

        dtoPage.setRecords(dtoList);
        return dtoPage;
    }

    @Override
    @Transactional
    public boolean approveReturnOrder(Long returnOrderId, String approvalRemark) {
        PurchaseReturnOrder returnOrder = getById(returnOrderId);
        if (returnOrder == null) {
            throw new RuntimeException("退货订单不存在");
        }

        if (returnOrder.getStatus() != 0) {
            throw new RuntimeException("只有待审核状态的退货订单可以审核");
        }

        returnOrder.setStatus(1); // 已审核
        returnOrder.setUpdatedAt(new Date());
        return updateById(returnOrder);
    }

    @Override
    @Transactional
    public boolean rejectReturnOrder(Long returnOrderId, String rejectReason) {
        PurchaseReturnOrder returnOrder = getById(returnOrderId);
        if (returnOrder == null) {
            throw new RuntimeException("退货订单不存在");
        }

        if (returnOrder.getStatus() != 0) {
            throw new RuntimeException("只有待审核状态的退货订单可以拒绝");
        }

        returnOrder.setStatus(3); // 已拒绝
        returnOrder.setUpdatedAt(new Date());
        return updateById(returnOrder);
    }

    @Override
    @Transactional
    public boolean processReturnOrder(Long returnOrderId, String processRemark) {
        PurchaseReturnOrder returnOrder = getById(returnOrderId);
        if (returnOrder == null) {
            throw new RuntimeException("退货订单不存在");
        }

        if (returnOrder.getStatus() != 1) {
            throw new RuntimeException("只有已审核状态的退货订单可以处理");
        }

        returnOrder.setStatus(2); // 已处理
        returnOrder.setUpdatedAt(new Date());
        return updateById(returnOrder);
    }

    @Override
    public List<PurchaseReturnOrder> getReturnOrdersBySalesOrderId(Long salesOrderId) {
        LambdaQueryWrapper<PurchaseReturnOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PurchaseReturnOrder::getSalesOrderId, salesOrderId);
        wrapper.orderByDesc(PurchaseReturnOrder::getCreatedAt);
        return list(wrapper);
    }

    @Override
    public String generateReturnOrderCode() {
        String timestamp = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        int random = (int) (Math.random() * 90) + 10;
        return "RO" + timestamp + random;
    }

    /**
     * 计算退货总金额
     */
    private void calculateReturnAmount(PurchaseReturnOrderDTO returnOrderDTO) {
        if (returnOrderDTO.getItems() == null || returnOrderDTO.getItems().isEmpty()) {
            returnOrderDTO.setTotalReturnAmount(BigDecimal.ZERO);
            return;
        }

        BigDecimal totalAmount = BigDecimal.ZERO;

        for (PurchaseReturnOrderItem item : returnOrderDTO.getItems()) {
            if (item.getReturnAmount() != null) {
                totalAmount = totalAmount.add(item.getReturnAmount());
            }
        }

        returnOrderDTO.setTotalReturnAmount(totalAmount);
    }
}
